package com.aiprompt.demos.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步任务配置类
 * 配置AI任务专用线程池，优化系统并发处理能力
 */
@Configuration
public class AsyncConfig {
    
    /**
     * AI任务专用线程池
     * 用于处理耗时的AI模型调用，避免阻塞主线程池
     */
    @Bean("aiTaskExecutor")
    public ThreadPoolTaskExecutor aiTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        // 核心线程数：基于CPU核心数，保证基本处理能力
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        
        // 最大线程数：AI调用是IO密集型，可以设置较大值
        executor.setMaxPoolSize(50);
        
        // 队列容量：缓冲等待的任务，防止瞬时高并发
        executor.setQueueCapacity(100);
        
        // 线程名前缀：便于日志追踪和问题定位
        executor.setThreadNamePrefix("AI-Task-");
        
        // 拒绝策略：队列满时让调用线程执行，保证任务不丢失
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        
        // 线程空闲时间：60秒后回收多余线程
        executor.setKeepAliveSeconds(60);
        
        // 优雅关闭：等待任务完成后关闭
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(30);
        
        executor.initialize();
        return executor;
    }
}
